package fetzu.app;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.TimeZone;

import org.apache.commons.io.IOUtils;
import org.jdesktop.application.Application;
import org.jdesktop.application.Task;

public class IpLookup {

	public static class Retriever extends Task<TimeZone[],Void> {

		public Retriever(Application application) {
			super(application);
		}

		@Override
		protected TimeZone[] doInBackground() throws Exception {
			lookup();
			String[] possibleIds = getPossibleIds();
			TimeZone[] possibleZones = new TimeZone[possibleIds.length];
			for (int i = 0; i < possibleIds.length; i++) {
				possibleZones[i] = TimeZone.getTimeZone(possibleIds[i]);
			}
			return possibleZones;
		}
	}

	static String lastResult;
	private static int hoursOffset;
	private static boolean isUnitedStates;
	final static String sourceUrlStr = "http://www.ip2location.com/ib1/";

	static void lookup() {
		try {
			URL sourceUrl = new URL(sourceUrlStr);
			InputStream input = sourceUrl.openStream();
			lastResult = IOUtils.toString(input, "UTF-8");

			isUnitedStates = lastResult.contains("UNITED STATES");
			// lookup in something like this:
			// </strong> Time Zone: <strong>UTC -05:00</strong> Net Speed:
			int startTimezone = lastResult.indexOf("Time Zone:");
			// assume it's always in the same place, relative to "Time Zone"
			int afterIndex = "Time Zone: <strong>UTC ".length();
			int offsetStrLength = "-05".length();
			String offsetStr = lastResult.substring(startTimezone + afterIndex,
					startTimezone + afterIndex + offsetStrLength);

			hoursOffset = Integer.parseInt(offsetStr);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static String[] getPossibleIds() {
		if (lastResult == null)
			return new String[] { "Error/Nowhere" };

		int millisOffset = hoursOffset * 60 * 60 * 1000;
		String[] availableIDs = TimeZone.getAvailableIDs(millisOffset);

		// the above can return lots of timezones
		// TODO let user choose between them
		
		if (availableIDs.length != 1 && isUnitedStates) {
			// then just convert by a this simple rule
			// this list is actually much longer:
			// http://en.wikipedia.org/wiki/List_of_zoneinfo_timezones
			switch (hoursOffset) {
			case -8:
				availableIDs = new String[] { "America/Los_Angeles" };
				break;
			case -7:
				availableIDs = new String[] { "America/Denver" };
				break;
			case -6:
				availableIDs = new String[] { "America/Chicago" };
				break;
			case -5:
				availableIDs = new String[] { "America/New_York" };
				break;
			}
		}
		return availableIDs;
	}

	// FIXME turn this into a test, each should have an answer but only 0 does
	// on Mac
	private static void queryAll() {
		for (int i = -8; i < 8; i++) {
			System.out.println("\nTime zones for " + i);
			String[] availableIDs = TimeZone.getAvailableIDs(i);
			for (String id : availableIDs) {
				System.out.println(id);
			}
		}
	}

	public static void main(String[] args) {
		queryAll();
		IpLookup.lookup();
		String[] possibleIds = IpLookup.getPossibleIds();
		for (String id : possibleIds) {
			System.out.println(id);
		}
	}

}
